package com.example.demo.controller;

import com.example.demo.config.MyRateLimiter;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import com.example.demo.utils.JwtUtils;
import com.example.demo.utils.Result;
import com.example.demo.utils.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
public class UserController {


    @Autowired
    MyRateLimiter myRateLimiter;

    @Autowired
    UserService userService;
    ResultCode resultCode = new ResultCode();

    @PostMapping("/login")
    // querystring: username=zhangsan&password=123  User user,String username,String password
    // json: {username:zhangsan,password:123}
    // 如果前端传递的数据是json格式，必须使用对象接收，同时需要添加@RequestBody
    public Result login(@RequestBody User user){
        Result res = new Result();

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //尝试获取令牌
        boolean acquire = myRateLimiter.tryAccountRegisterAcquire();
        System.out.println(Thread.currentThread().getName() + " login 尝试获取令牌结果"+acquire);
        if (acquire) {

            Map<String, Object> map = new HashMap<>();
            System.out.println("username"+user.getUsername()+"password"+user.getPassword());
            try {
                User info = userService.LoginIn(user.getUsername(),user.getPassword());
                if(info!=null){
                    String token = JwtUtils.generateToken (user.getUsername());
                    map.put("token",token);
                    res.setMessage("登录成功");
                    res.setData(map);
                }else {
                    res.setCode(ResultCode.LOGINERROR);
                    res.setMessage(resultCode.getMsg(ResultCode.LOGINERROR));
                }
            } catch (Exception e) {
                e.printStackTrace();
                res.setCode(ResultCode.ERROR);
                res.setMessage(resultCode.getMsg(ResultCode.ERROR));
            }
            System.out.println(Thread.currentThread().getName()+" login 成功拿到令牌 [" +  dtf.format(LocalDateTime.now()) + "]");
            return res;
        }
        System.out.println(Thread.currentThread().getName()+" login 被限制了 [" +  dtf.format(LocalDateTime.now())+ "]");
        return res;
    }

    @GetMapping("/info")  // "token:xxx"
    public Result info(String token){
        Result res = new Result();

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //尝试获取令牌
        boolean acquire = myRateLimiter.tryAccountRegisterAcquire();
        System.out.println(Thread.currentThread().getName() + " info 尝试获取令牌结果"+acquire);
        if (acquire) {
            Map<String, Object> map = new HashMap<>();
            try {
                String username = JwtUtils.getClaimsByToken(token).getSubject();
                User user = userService.getInfo(username);
                if(user!=null){
                    String url = "https://inews.gtimg.com/newsapp_bt/0/14732133311/641";
                    map.put("id",user.getId());
                    map.put("username",username);
                    map.put("password",user.getPassword());
                    map.put("email",user.getEmail());
                    map.put("avatar",url);
                    res.setMessage("返回成功");
                    res.setData(map);
                }else {
                    res.setCode(ResultCode.INFOERROR);
                    res.setMessage(resultCode.getMsg(ResultCode.INFOERROR));
                }
            } catch (Exception e) {
                e.printStackTrace();
                res.setCode(ResultCode.ERROR);
                res.setMessage(resultCode.getMsg(ResultCode.ERROR));
            }
            System.out.println(Thread.currentThread().getName()+" info 成功拿到令牌 [" +  dtf.format(LocalDateTime.now()) + "]");
            return res;
        }
        System.out.println(Thread.currentThread().getName()+" info 被限制了 [" +  dtf.format(LocalDateTime.now())+ "]");
        return res;
    }

    @GetMapping("/userList")
    public Result userList(@RequestParam(required = false, value="username")String username){
        Result res = new Result();

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //尝试获取令牌
        boolean acquire = myRateLimiter.tryAccountRegisterAcquire();
        System.out.println(Thread.currentThread().getName() + "userList 尝试获取令牌结果"+acquire);
        if (acquire) {
            System.out.println(username);
            Map<String, Object> map = new HashMap<String, Object>();
            try {
                List<User> list = userService.getUserList(username);
                map.put(" userlist",list);
                res.setMessage("返回成功");
                res.setData(map);
            } catch (Exception e) {
                e.printStackTrace();
                res.setCode(resultCode.ERROR);
                res.setMessage(resultCode.getMsg(resultCode.ERROR));
            }

            System.out.println(Thread.currentThread().getName()+" userList 成功拿到令牌 [" +  dtf.format(LocalDateTime.now()) + "]");
            return res;
        }
        System.out.println(Thread.currentThread().getName()+" userList 被限制了 [" +  dtf.format(LocalDateTime.now())+ "]");
        return res;
    }

    @PostMapping("/logout")  // "token:xxx"
    public Result logout(){
        Result res = new Result();

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //尝试获取令牌
        boolean acquire = myRateLimiter.tryAccountRegisterAcquire();
        System.out.println(Thread.currentThread().getName() + " logout 尝试获取令牌结果"+acquire);
        if (acquire) {
            res.setMessage("登出成功");
            System.out.println(Thread.currentThread().getName()+" logout 成功拿到令牌 [" +  dtf.format(LocalDateTime.now()) + "]");
            return res;
        }
        System.out.println(Thread.currentThread().getName()+" logout 被限制了 [" +  dtf.format(LocalDateTime.now())+ "]");
        return res;
    }

    //  用户注册
    @PostMapping("/register")
    public Result register(@RequestBody User user){
        Result res = new Result();

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //尝试获取令牌
        boolean acquire = myRateLimiter.tryAccountRegisterAcquire();
        System.out.println(Thread.currentThread().getName() + " register 尝试获取令牌结果"+acquire);
        if (acquire) {
            try {
                System.out.println("user"+user);
                int r = userService.register(user);
                if(r > 0){
                    res.setMessage("注册成功");
                }else{
                    res.setCode(ResultCode.REGERROR);
                    res.setMessage(resultCode.getMsg(ResultCode.REGERROR));
                }
            } catch (Exception e) {
                e.printStackTrace();
                res.setCode(ResultCode.ERROR);
                res.setMessage(resultCode.getMsg(ResultCode.ERROR));
            }
            System.out.println(Thread.currentThread().getName()+" register 成功拿到令牌 [" +  dtf.format(LocalDateTime.now()) + "]");
            return res;
        }
        System.out.println(Thread.currentThread().getName()+" register 被限制了 [" +  dtf.format(LocalDateTime.now())+ "]");
        return res;
    }

    // 更新用户信息
    @PutMapping("/updateUser")
    public Result update(@RequestBody User user){
        Result res = new Result();

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //尝试获取令牌
        boolean acquire = myRateLimiter.tryAccountRegisterAcquire();
        System.out.println(Thread.currentThread().getName() + " updateUser 尝试获取令牌结果"+acquire);
        if (acquire) {
            try {
                int r = userService.update(user);
                if(r > 0){
                    res.setMessage("用户信息更新成功");
                }else{
                    res.setCode(ResultCode.UPDATEERROR);
                    res.setMessage(resultCode.getMsg(ResultCode.UPDATEERROR));
                }
            } catch (Exception e) {
                e.printStackTrace();
                res.setCode(ResultCode.ERROR);
                res.setMessage(resultCode.getMsg(ResultCode.ERROR));
            }

            System.out.println(Thread.currentThread().getName()+" updateUser 成功拿到令牌 [" +  dtf.format(LocalDateTime.now()) + "]");
            return res;
        }
        System.out.println(Thread.currentThread().getName()+" updateUser 被限制了 [" +  dtf.format(LocalDateTime.now())+ "]");
        return res;
    }

    @DeleteMapping("/deleteUser")
    public Result delete(@RequestParam(required = true,value = "id") Integer id){
        Result res = new Result();

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //尝试获取令牌
        boolean acquire = myRateLimiter.tryAccountRegisterAcquire();
        System.out.println(Thread.currentThread().getName() + " deleteUser 尝试获取令牌结果"+acquire);
        if (acquire) {
            try {
                System.out.println("id===="+id);
                int r = userService.delete(id);
                if(r>0){
                    res.setMessage("用户信息删除成功");
                }else {
                    res.setCode(ResultCode.DELETEERROR);
                    res.setMessage(resultCode.getMsg(ResultCode.DELETEERROR));
                }
            }catch (Exception e){
                e.printStackTrace();
                res.setCode(ResultCode.ERROR);
                res.setMessage(resultCode.getMsg(ResultCode.ERROR));
            }
            System.out.println(Thread.currentThread().getName()+" deleteUser 成功拿到令牌 [" +  dtf.format(LocalDateTime.now()) + "]");
            return res;
        }
        System.out.println(Thread.currentThread().getName()+" deleteUser 被限制了 [" +  dtf.format(LocalDateTime.now())+ "]");
        return res;
    }
}
